package com.gexiaobao.pigeon.ui.fragment.mine.banking

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentAccountSigningBinding
import com.gexiaobao.pigeon.viewmodel.MineBankingViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.util.LogUtils

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 10:17
 * @Describe    : 电子签约
 */
class FragmentAccountSigning : BaseFragment<MineBankingViewModel, FragmentAccountSigningBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.toolbar.initClose("电子签约") {
            nav().navigateUp()
        }
        mViewModel.signAcctProtocol()
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.accountSignResult.observe(viewLifecycleOwner) { resultState ->
            parseState(resultState, {
                initWebView(it.toUrl)
            }, {
                RxToast.showToast(it.msg)
            })
        }
    }

    @SuppressLint("JavascriptInterface")
    private fun initWebView(toUrl: String) {
        val webViewHeaderValue = KvUtils.decodeString(Constant.TOKEN)
        LogUtils.debugInfo(toUrl)
        val map = mapOf("x-token" to webViewHeaderValue)
        mDatabind.webView.loadUrl(toUrl, map)
        val webSettings = mDatabind.webView.settings
        webSettings.userAgentString += "Android-Pigeon"
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不使用缓存，只从网络获取数据.
        //支持屏幕缩放
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        //扩大比例的缩放
        webSettings.useWideViewPort = true
        // 自适应屏幕
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true//设置js可以直接打开窗口，如window.open()，默认为false
        webSettings.javaScriptEnabled = true//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webSettings.setSupportZoom(true)//是否可以缩放，默认true
        webSettings.builtInZoomControls = false//是否显示缩放按钮，默认false
        webSettings.useWideViewPort = true//设置此属性，可任意比例缩放。大视图模式
        webSettings.loadWithOverviewMode = true//和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.domStorageEnabled = true//DOM Storage
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW//加载https和http混合模式

        mDatabind.webView.addJavascriptInterface(this, "android");//添加js监听 这样html就能调用客户端
        mDatabind.webView.webChromeClient = webChromeClient
        mDatabind.webView.webViewClient = webViewClient
    }

    private val webViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView, url: String) {//页面加载完成
        }

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            try {
                if (url.startsWith("https://www.baidu.com")) {
                    nav().navigateUp()
                    return false
                }
                return super.shouldOverrideUrlLoading(view, url)
            } catch (e: Exception) {
                e.printStackTrace()
                return false
            }
        }
    }

    private val webChromeClient: WebChromeClient = object : WebChromeClient() {

        override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            return super.onJsAlert(view, url, message, result)
        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            if (mDatabind.progressBar != null) {
                mDatabind.progressBar.visibility = View.VISIBLE
                mDatabind.progressBar.progress = newProgress
                if (newProgress == 100) {
                    mDatabind.progressBar.visibility = View.GONE
                }
            }
        }
    }

    override fun onDestroyView() {
        mDatabind.webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        mDatabind.webView.clearHistory()
        mDatabind.webView.destroy()
        super.onDestroyView()
    }
}